import Vue from "vue";
import axios from "axios";
import {VueAxios} from "./axios";
import {Message, Notification} from "element-ui";
import store from "../store";
import VueCookie from "vue-cookies";

// axios.defaults.withCredentials = true
// 创建 axios 实例
const service = axios.create({
    baseURL: process.env.NODE_ENV === "production" ? "" : "http://localhost:8080",
    withCredentials: true,

});
// service.defaults.withCredentials=true;
console.log(process.env.NODE_ENV);
const err = (error) => {
    if (error.response) {
        const data = error.response.data;
        const token = Vue.ls.get("ACCESS_TOKEN");
        if (error.response.status === 403) {
            Notification.error({
                title: "Forbidden",
                message: data.message
            });
        }
        if (error.response.status === 401 && !(data.result && data.result.isLogin)) {
            Notification.error({
                title: "Unauthorized",
                message: "Authorization verification failed"
            });
            if (token) {
                store.dispatch("Logout").then(() => {
                    setTimeout(() => {
                        window.location.reload();
                    }, 1500);
                });
            }
        }
    }
    return Promise.reject(error);
};

//request 拦截器
service.interceptors.request.use((config) => {
    // config.withCredentials=true
    if (VueCookie.get("Authorization") != null
        && config.url !== "http://101.200.57.150:8001/login"
        && config.url.substr(27, 4) !== "user"
        && config.url !== "http://101.200.57.150:8001/get_one_captcha"
        && config.url.substr(0, 26) !== "http://120.46.154.112:7903"
    ) {
        config.headers.authorization = VueCookie.get("Authorization");

    }
    return config;
}, err);

service.interceptors.response.use((response) => {
    switch (response.status) {
        case 200:
            VueCookie.set("Authorization", response.headers.authorization);

            return response.data;
        case 404:
            return false;
        default:
            Message.error("调用出错啦！");
    }
});

const installer = {
    vm: {},
    install(Vue) {
        Vue.use(VueAxios, service);
    }
};

export {
    installer as VueAxios,
    service as axios
};
